package be.phl.mycinema;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import be.phl.mycinema.classes.Gebruiker;

import com.google.gson.Gson;

public class RegistratieActivity extends Activity implements OnClickListener {

	private final static String TAG = "REGISTRATIE";
	private TextView txtVoornaam;
	private TextView txtAchternaam;
	private TextView txtWachtwoord;
	private TextView txtEmail;
	private TextView txtGeboortedatum;
	private Context myContext = this;
	private Button btnRegistratie;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_registratie);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		
		txtVoornaam = (TextView) findViewById(R.id.registratie_txtVoornaam);
		txtAchternaam = (TextView) findViewById(R.id.registratie_txtAchternaam);
		txtEmail = (TextView) findViewById(R.id.registratie_txtEmail);
		txtWachtwoord = (TextView) findViewById(R.id.registratie_txtWachtwoord);
		txtGeboortedatum = (TextView) findViewById(R.id.registratie_txtGeboortedatum);

		btnRegistratie = (Button) findViewById(R.id.registratie_btnRegistreer);
		btnRegistratie.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.registratie_btnRegistreer:
			
			String email = txtEmail.getText() == null ? null : txtEmail.getText().toString();			
			
			if (txtVoornaam.getText().equals("") || txtAchternaam.getText().equals("") || txtEmail.getText().equals("") || txtWachtwoord.getText().equals("") || txtGeboortedatum.getText().equals("")) {
				Toast.makeText(myContext, "Vul alle velden in!", Toast.LENGTH_LONG).show();
				return;
			} else if (txtVoornaam.getText().length() < 2 || txtVoornaam.getText().length() > 25) {
				Toast.makeText(myContext, "Voornaam is incorrect. (25>x>2)", Toast.LENGTH_LONG).show();
				return;
			} else if (txtAchternaam.getText().length() < 2 || txtAchternaam.getText().length() > 25) {
				Toast.makeText(myContext, "Achternaam is incorrect. (25>x>2)", Toast.LENGTH_LONG).show();
				return;
			} else if (email == null || email.length() < 9 || email.length() > 50 || email.contains("@") == false || email.contains(".") == false) {
				Toast.makeText(myContext, "E-mailadres is incorrect.", Toast.LENGTH_LONG).show();
				return;
			} else if (txtWachtwoord.getText().length() < 6 || txtWachtwoord.getText().length() > 25) {
				Toast.makeText(myContext, "Wachtwoord is incorrect. (25>x>6)", Toast.LENGTH_LONG).show();
				return;
			} else if (txtGeboortedatum.getText().length() < 2 || txtGeboortedatum.getText().length() > 25) {
				Toast.makeText(myContext, "Geboortedatum is incorrect. (dd-mm-jjjj)", Toast.LENGTH_LONG).show();
				return;
			} else {
				//Geavanceerdere controles op geboortedatum en email
				
				int aap = email.indexOf("@");
				int dot = email.lastIndexOf(".");
				
				if (aap >= dot || aap+2 >= dot) {
					Toast.makeText(myContext, "E-mailadres is incorrect.", Toast.LENGTH_LONG).show();
					return;
				}
				
				SimpleDateFormat fDate = new SimpleDateFormat("dd-MM-yyyy");
				String date = txtGeboortedatum.getText() == null ? null : txtGeboortedatum.getText().toString();		
				
				Date early = null;
				Date now = null;
				Calendar cal = GregorianCalendar.getInstance();
				now = cal.getTime();
				cal.set(1900, 01, 01);
				early = cal.getTime();
				
				try {
					Date testDate = fDate.parse(date);
					if (! fDate.format(testDate).equals(date)) {
						Toast.makeText(myContext, "Geboortedatum is incorrect. (dd-mm-jjjj)", Toast.LENGTH_LONG).show();
						return;
					} else if (testDate.after(now) || testDate.before(early)) {
						Toast.makeText(myContext, "Geboortedatum is incorrect. (dd-mm-jjjj)", Toast.LENGTH_LONG).show();
						return;
					}
				} catch (ParseException e) {
					Toast.makeText(myContext, "Geboortedatum is incorrect. (dd-mm-jjjj)", Toast.LENGTH_LONG).show();
					return;
				}
			}
			
			if (! Utils.isNetworkAvailable((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))) {
				Toast.makeText(myContext, "Er is geen internetverbinding beschikbaar!", Toast.LENGTH_LONG).show();
			} else if (! Utils.isWebserviceAvailable()) {
				Toast.makeText(getBaseContext(), "De server is niet bereikbaar, probeer later opnieuw.", Toast.LENGTH_LONG).show();
			} else {
				new doAsyncTask().execute(Utils.WEBSERVICE_BASE_ADDRESS + "/gebruiker");
			}
			
			break;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		case android.R.id.home:			
				finish();
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	private class doAsyncTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			try {
				Log.d(TAG,"Creating gebruiker object");
				Gebruiker gebruiker = new Gebruiker();
				gebruiker.setVoornaam(txtVoornaam.getText().toString());
				gebruiker.setAchternaam(txtAchternaam.getText().toString());
				gebruiker.setWachtwoord_hash(txtWachtwoord.getText().toString());
				gebruiker.setEmail(txtEmail.getText().toString());
				
				final String OLD_FORMAT = "dd-MM-yyyy";
				final String NEW_FORMAT = "yyyy-MM-dd";

				String oldDateString = txtGeboortedatum.getText().toString();
				String newDateString;

				SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
				Date d = sdf.parse(oldDateString);
				sdf.applyPattern(NEW_FORMAT);
				newDateString = sdf.format(d);
				
				gebruiker.setGeboortedatum(newDateString);
				
				Gson g = new Gson();
				String jsonString = g.toJson(gebruiker);

				HttpURLConnection con;
				URL url = new URL(params[0]);
				
				con = (HttpURLConnection) url.openConnection();
				con.setDoOutput(true);
				con.setRequestMethod("POST");
				con.setFixedLengthStreamingMode(jsonString.getBytes().length);
				con.setRequestProperty("Content-Type", "application/json");
				
				OutputStream out = con.getOutputStream();
				out.write(jsonString.getBytes());
				out.close();
							
				int responsecode = con.getResponseCode();
				Log.d(TAG, String.valueOf(responsecode));
				
				if(responsecode == 200) {
					Log.d(TAG,"Registratie succes");
					return true;
				}
				
			} catch (Exception e) {
				Log.e(TAG, e.getMessage());
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			
			if(result) {
				Toast.makeText(myContext, "Registratie voltooid. U kan nu aanmelden!", Toast.LENGTH_LONG).show();
				SharedPreferences prefs = getSharedPreferences("be.phl.mycinema.userinfo", MODE_PRIVATE);
				Editor prefEditor = prefs.edit();
				prefEditor.clear();
				prefEditor.commit();
				Intent i = new Intent(getBaseContext(),LoginActivity.class);
				startActivity(i);
			} else {
				Toast.makeText(myContext, "Er zijn foutieve gegevens ingegeven!", Toast.LENGTH_LONG).show();
				Log.d(TAG, "Registratie is niet gelukt..");
			}
		}
	}
	
    @Override
    public void onBackPressed() {
    	// Back button disabled
    }
}
